namespace ClassyBlog.Infrastructure
{
    using System;
    using System.Web;
    using System.Web.Routing;

    public class PositiveIntegerConstraint : IRouteConstraint
    {
        public PositiveIntegerConstraint() : this(false)
        {
        }

        public PositiveIntegerConstraint(bool optional)
        {
            Optional = optional;
        }

        protected bool Optional { get; private set; }

        public bool Match(
            HttpContextBase httpContext,
            Route route,
            string parameterName,
            RouteValueDictionary values,
            RouteDirection routeDirection)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }

            if (!values.ContainsKey(parameterName) ||
                string.IsNullOrWhiteSpace(values[parameterName].ToString()))
            {
                return Optional;
            }

            int value;

            return int.TryParse(
                values[parameterName].ToString(), out value) && (value > 0);
        }
    }
}